package org.lql.algo.codecrush.week004;

import java.util.Arrays;
import java.util.Stack;

/**
 * @author: liangqinglong
 * @date: 2025-08-01 17:49
 * @description: 739. 每日温度 <a href="https://leetcode.cn/problems/daily-temperatures/description/">...</a>
 **/
public class DailyTemperatures {

	/**
	 * 给定一个整数数组 temperatures ，表示每天的温度，返回一个数组 answer ，
	 * 其中 answer[i] 是指对于第 i 天，下一个更高温度出现在几天后。如果气温在这之后都不会升高，请在该位置用 0 来代替。
	 * <p>
	 * <p>
	 * <p>
	 * 示例 1:
	 * <p>
	 * 输入: temperatures = [73,74,75,71,69,72,76,73]
	 * 输出: [1,1,4,2,1,1,0,0]
	 * 示例 2:
	 * <p>
	 * 输入: temperatures = [30,40,50,60]
	 * 输出: [1,1,1,0]
	 * 示例 3:
	 * <p>
	 * 输入: temperatures = [30,60,90]
	 * 输出: [1,1,0]
	 * <p>
	 * <p>
	 * 提示：
	 * <p>
	 * 1 <= temperatures.length <= 105
	 * 30 <= temperatures[i] <= 100
	 */

	public int[] dailyTemperatures(int[] temperatures) {
		int[] result = new int[temperatures.length];
		for (int i = 0; i < temperatures.length; i++) {
			for (int j = i + 1; j < temperatures.length; j++) {
				if (temperatures[j] > temperatures[i]) {
					result[i] = j - i;
					break;
				}
			}
			if (result[i] == 0) {
				result[i] = 0;
			}
		}
		return result;
	}

	public int[] dailyTemperatures2(int[] temperatures) {
		int[] result = new int[temperatures.length];
		Stack<Integer> stack = new Stack<>();
		for (int i = 0; i < temperatures.length; i++) {
			while (!stack.isEmpty() && temperatures[i] > temperatures[stack.peek()]) {
				int index = stack.pop();
				result[index] = i - index;
			}
			stack.push(i);
		}
		return result;
	}

	public int[] dailyTemperatures3(int[] temperatures) {
		int[] result = new int[temperatures.length];
		Stack<Integer> stack = new Stack<>();
		for (int i = temperatures.length - 1; i >= 0; i--) {
			while (!stack.isEmpty() && temperatures[i] >= temperatures[stack.peek()]) {
				stack.pop();
			}
			if (!stack.isEmpty()) {
				result[i] = stack.peek() - i;
			}
			stack.push(i);
		}
		return result;
	}

	public static void main(String[] args) {
		DailyTemperatures dailyTemperatures = new DailyTemperatures();
		int[] temperatures = {73, 74, 75, 71, 69, 72, 76, 73};
		int[] result = dailyTemperatures.dailyTemperatures(temperatures);
		System.out.println(Arrays.toString(result));
		int[] result2 = dailyTemperatures.dailyTemperatures2(temperatures);
		System.out.println(Arrays.toString(result2));
		int[] result3 = dailyTemperatures.dailyTemperatures3(temperatures);
		System.out.println(Arrays.toString(result3));
	}
}
